package util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * User: key
 * ClassName:DbUtils
 * Date: 2023/5/6
 * Time: 13:47
 * description:
 */
public class DbUtils {
    private static final ThreadLocal<Connection> T = new ThreadLocal<>();
    private static DruidDataSource ds;

    static {
        Properties pro = new Properties();
        try {
            pro.load(DbUtils.class.getResourceAsStream("/jdbc.properties"));
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection con = T.get();
        try {
            if (con == null) {
                con = ds.getConnection();
                T.set(con);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    public static DataSource getDataSource() {
        return ds;
    }

    public static void closeAll(ResultSet rs, PreparedStatement ps, Connection con) {
        try {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
            if (con != null) {
                con.close();
                T.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void begin() {
        Connection con = getConnection();
        try {
            con.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit() {
        Connection con = getConnection();
        try {
            con.commit();
            closeAll(null, null, con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback() {
        Connection con = getConnection();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        closeAll(null, null, con);
    }
}
